<template>
    <div class="login">
        <el-form ref="loginRef" class="login-form" :model="loginForm" :rules="loginRules">
            <h3 class="title">后台管理系统</h3>
            <el-form-item prop="username">
                <el-input 
                v-model="loginForm.username" 
                type="text" 
                size="large" 
                placeholder="账号" 
                :prefix-icon="User"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input 
                v-model="loginForm.password" 
                type="password" 
                size="large" 
                placeholder="密码" 
                :prefix-icon="Lock"></el-input>
            </el-form-item>
            <el-form-item prop="code">
                <el-input
                color="red"
                v-model="loginForm.code" 
                size="large" 
                auto-complete="off" 
                placeholder="验证码" 
                style="flex: 1"
                :prefix-icon="CircleCheck"></el-input>
                <div class="login-code">
                    <img :src="codeImgUrl" @click="getCode" class="login-code-img"/>
                </div>
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
            </el-form-item>
            <el-form-item style="width:100%;">
                <el-button
                :loading="loading"
                size="large"
                type="primary"
                style="width:100%;"
                @click.prevent="handleLogin"
                >
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
                </el-button>
                <div style="float: right;" v-if="register">
                <router-link class="link-type" :to="'/register'">立即注册</router-link>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>
<script lang="ts">
import { defineComponent, getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
import { ElForm, ElFormItem, ElInput,ElCheckbox,ElButton, FormInstance, ElMessageBox } from 'element-plus'
import { User, Lock,CircleCheck } from '@element-plus/icons-vue'
import Cookies from "js-cookie"
import ApiHelper from '@/api/ApiHelper'
import {Md5} from 'ts-md5'
import router from '@/router'
import { getToken } from '@/utils/request'
import { getImageVerificationCodeUrl } from '@/const'

export default defineComponent({
    name: 'LoginView',
    components: { ElForm, ElFormItem, ElInput,ElCheckbox,ElButton },
    setup() {
        let salt:string
        const loginRef=ref<FormInstance>()
        const register = ref(false)
        const loading = ref(false)
        const loginForm = reactive({
            username: "admin",
            password: "123456",
            rememberMe: false,
            code: "",
            uuid: ""
        })
        const codeImgUrl=ref('')
        const getCode=()=>{
            codeImgUrl.value=getImageVerificationCodeUrl()
        }
        const handleLogin=()=>{
            //console.log(loginRef.value)
            loginRef.value?.validate((valid:any)=> {
                //console.log(valid)
                if (valid) {
                    loading.value = true
                    // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
                    if (loginForm.rememberMe) {
                        Cookies.set("username", loginForm.username, { expires: 30 })
                        Cookies.set("password", Md5.hashStr(loginForm.password+salt), { expires: 30 })
                        Cookies.set("rememberMe", loginForm.rememberMe+'', { expires: 30 })
                    } else {
                        // 否则移除
                        Cookies.remove("username")
                        Cookies.remove("password")
                        Cookies.remove("rememberMe")
                    }
                    ApiHelper.getInstance().login(loginForm.username,Md5.hashStr(loginForm.password+salt),loginForm.code).then((res:any)=>{
                        console.log(res)
                        loading.value = false
                        const redirect=getQueryValue()
                        console.log(redirect)
                        if(redirect){
                            location.href=redirect
                        }else{
                            router.push('/')
                        }
                    }).catch((err:any)=>{
                        loading.value = false
                        ElMessageBox.alert(err, '提示', { type: 'error' })
                        //console.log(err)
                    })
                }
            })
        }
        const loginRules = {
            username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
            password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
            code: [{ required: true, trigger: "change", message: "请输入验证码" }]
        }
        const getSalt=()=>{
            console.log('getSalt')
            ApiHelper.getInstance().getSalt(loginForm.username).then((res:any)=>{
                console.log('获取盐值',res.salt)
                salt=res.salt
            }).catch((err)=>{
                console.log(err)
            })
        }
        onMounted(()=>{
            console.log('获取token',getToken())
            if(getToken()){
                ApiHelper.getInstance().getUserInfo().then((res:any)=>{
                    console.log('getUserInfo',res)
                })
                router.push('/')
            }else{
                getCode()
            }
            watch(()=>loginForm.username,(newValue, oldValue)=>{
                getSalt()
            })
            getSalt()
        })
        return { User, Lock,CircleCheck, loginForm, getCode,loading,handleLogin,register,codeImgUrl,loginRules,loginRef }
    }
})
const getQueryValue=(name='redirect')=>{
    const query = window.location.search
    const params = new URLSearchParams(query)
    return params.get(name)
}
</script>
<style lang='scss' scoped>
.login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url("../assets/images/background.jpg");
    background-size: cover;
}

.login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;
    .el-input {
        height: 40px;
        input {
            height: 40px;
        }
    }
    .input-icon {
        height: 39px;
        width: 14px;
        margin-left: 0px;
    }
}</style>